package com.qc.chat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.qc.common.JSONUtil;
import com.qc.entity.message.ChatListEntity;
import com.qc.entity.message.ChatMessageEntity;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ChatListMember implements Serializable {

	public static Map<Long, List<ChatListEntity>> chatListMap = new HashMap<Long, List<ChatListEntity>>();// 用户所有的聊天列表
	
	public static String cacheFileName = "cacheMessage.txt";

	private ChatListMember() {
	}

	private static ChatListMember single = null;

	public static ChatListMember getInstance() {
		if (single == null) {
			synchronized (ChatListMember.class) {
				if (single == null) {
					single = new ChatListMember();
				}
			}
		}
		return single;
	}
	
	/**
	 * 默认发送的消息不给发送者列表加
	 * @param entity
	 */
	public static void defaultSenderMessage(ChatMessageEntity entity) {
		//处理对方的列表
		List<ChatListEntity> list = ChatListMember.chatListMap.get(entity.getTargetId());

		if(list!=null && !list.isEmpty()){
			boolean flag = false;
			for (ChatListEntity chatListEntity : list) {
				if (chatListEntity.getTargetId() == entity.getSenderId()) {
					chatListEntity.setUnReadNum(chatListEntity.getUnReadNum() + 1);
					chatListEntity.setContent(entity.getContent());
					chatListEntity.setSendTime(entity.getSendTime());
					chatListEntity.setCategory(entity.getCategory());
					chatListEntity.setContentType(entity.getContentType());
					chatListEntity.getMsgList().add(entity);
					flag = true;
				}
			}
			if (flag == false) {
				ChatListEntity listEntity = new ChatListEntity();
				listEntity.setTargetId(entity.getSenderId());
				listEntity.setUnReadNum(1);
				listEntity.setContent(entity.getContent());
				listEntity.setSendTime(entity.getSendTime());
				listEntity.setContentType(entity.getContentType());
				listEntity.setNickname(entity.getSenderNickname());
				listEntity.setCategory(entity.getCategory());
				listEntity.setAvatar(entity.getSenderAvatar());
				listEntity.getMsgList().add(entity);
				list.add(listEntity);
			}
		} else {
			List<ChatListEntity> l = new ArrayList<ChatListEntity>();
			ChatListEntity listEntity = new ChatListEntity();
			listEntity.setTargetId(entity.getSenderId());
			listEntity.setUnReadNum(1);
			listEntity.setContent(entity.getContent());
			listEntity.setSendTime(entity.getSendTime());
			listEntity.setContentType(entity.getContentType());
			listEntity.setNickname(entity.getSenderNickname());
			listEntity.setCategory(entity.getCategory());
			listEntity.setAvatar(entity.getSenderAvatar());
			listEntity.getMsgList().add(entity);
			l.add(listEntity);
			ChatListMember.chatListMap.put(entity.getTargetId(), l);
		}		
	}
	
	/**
	 * 发一个消息处理逻辑
	 * 1，需要修改自己的列表
	 * 2，需要修改对方的列表
	 * @param entity
	 */
	public static void senderMessage(ChatMessageEntity entity) {
		if(entity.getSenderId() != 0) {
			//处理自己的列表
			List<ChatListEntity> myChatListEntities = ChatListMember.chatListMap.get(entity.getSenderId());
//			updateChatList(entity, myChatListEntities, entity.getTargetId());
			
			if(myChatListEntities!=null && !myChatListEntities.isEmpty()){
				boolean flag = false;
				for (ChatListEntity chatListEntity : myChatListEntities) {
					if (chatListEntity.getTargetId() == entity.getTargetId()) {
						chatListEntity.setUnReadNum(0);
						chatListEntity.setContent(entity.getContent());
						chatListEntity.setSendTime(entity.getSendTime());
						chatListEntity.setCategory(entity.getTargetCategory());
						chatListEntity.setContentType(entity.getContentType());
						chatListEntity.getMsgList().add(entity);
						flag = true;
					}
				}
				if (flag == false) {
					ChatListEntity listEntity = new ChatListEntity();
					listEntity.setTargetId(entity.getTargetId());
					listEntity.setUnReadNum(0);
					listEntity.setContent(entity.getContent());
					listEntity.setSendTime(entity.getSendTime());
					listEntity.setContentType(entity.getContentType());
					listEntity.setNickname(entity.getTargetNickname());
					listEntity.setCategory(entity.getTargetCategory());
					listEntity.setAvatar(entity.getTargetAvatar());
					listEntity.getMsgList().add(entity);
					myChatListEntities.add(listEntity);
				}
			} else {
				List<ChatListEntity> l = new ArrayList<ChatListEntity>();
				ChatListEntity listEntity = new ChatListEntity();
				listEntity.setTargetId(entity.getTargetId());
				listEntity.setUnReadNum(0);
				listEntity.setContent(entity.getContent());
				listEntity.setSendTime(entity.getSendTime());
				listEntity.setContentType(entity.getContentType());
				listEntity.setNickname(entity.getTargetNickname());
				listEntity.setCategory(entity.getTargetCategory());
				listEntity.setAvatar(entity.getTargetAvatar());
				listEntity.getMsgList().add(entity);
				l.add(listEntity);
				ChatListMember.chatListMap.put(entity.getSenderId(), l);
			}
		}
		
		if(entity.getTargetId() != 0) {
			//处理对方的列表
			List<ChatListEntity> list = ChatListMember.chatListMap.get(entity.getTargetId());
//			updateChatList(entity, list, entity.getSenderId());
			
			if(list!=null && !list.isEmpty()){
				boolean flag = false;
				for (ChatListEntity chatListEntity : list) {
					if (chatListEntity.getTargetId() == entity.getSenderId()) {
						chatListEntity.setUnReadNum(chatListEntity.getUnReadNum() + 1);
						chatListEntity.setContent(entity.getContent());
						chatListEntity.setSendTime(entity.getSendTime());
						chatListEntity.setCategory(entity.getCategory());
						chatListEntity.setContentType(entity.getContentType());
						chatListEntity.getMsgList().add(entity);
						flag = true;
					}
				}
				if (flag == false) {
					ChatListEntity listEntity = new ChatListEntity();
					listEntity.setTargetId(entity.getSenderId());
					listEntity.setUnReadNum(1);
					listEntity.setContent(entity.getContent());
					listEntity.setSendTime(entity.getSendTime());
					listEntity.setContentType(entity.getContentType());
					listEntity.setNickname(entity.getSenderNickname());
					listEntity.setCategory(entity.getCategory());
					listEntity.setAvatar(entity.getSenderAvatar());
					listEntity.getMsgList().add(entity);
					list.add(listEntity);
				}
			} else {
				List<ChatListEntity> l = new ArrayList<ChatListEntity>();
				ChatListEntity listEntity = new ChatListEntity();
				listEntity.setTargetId(entity.getSenderId());
				listEntity.setUnReadNum(1);
				listEntity.setContent(entity.getContent());
				listEntity.setSendTime(entity.getSendTime());
				listEntity.setContentType(entity.getContentType());
				listEntity.setNickname(entity.getSenderNickname());
				listEntity.setCategory(entity.getCategory());
				listEntity.setAvatar(entity.getSenderAvatar());
				listEntity.getMsgList().add(entity);
				l.add(listEntity);
				ChatListMember.chatListMap.put(entity.getTargetId(), l);
			}
		}
		
	}
	
	/**
	 * 处理单个人的聊天列表对象，以及聊天数据
	 * @param entity(消息发送者实体)
	 * @param list(待处理的聊天列表)
	 * @param userId(表示userId或者targetId)
	 */
	public static void updateChatList(ChatMessageEntity entity, List<ChatListEntity> list, Long userId) {
		if(list!=null && !list.isEmpty()){
			boolean flag = false;
			for (ChatListEntity chatListEntity : list) {
				if (chatListEntity.getTargetId() == userId) {
					chatListEntity.setUnReadNum(chatListEntity.getUnReadNum() + 1);
					chatListEntity.setContent(entity.getContent());
					chatListEntity.setSendTime(entity.getSendTime());
					chatListEntity.setCategory(entity.getCategory());
					chatListEntity.setContentType(entity.getContentType());
					chatListEntity.getMsgList().add(entity);
					flag = true;
				}
			}
			if (flag == false) {
				ChatListEntity listEntity = new ChatListEntity();
				listEntity.setTargetId(entity.getSenderId());
				listEntity.setUnReadNum(1);
				listEntity.setContent(entity.getContent());
				listEntity.setSendTime(entity.getSendTime());
				listEntity.setContentType(entity.getContentType());
				listEntity.setNickname(entity.getSenderNickname());
				listEntity.setCategory(entity.getCategory());
				listEntity.setAvatar(entity.getSenderAvatar());
				listEntity.getMsgList().add(entity);
				list.add(listEntity);
			}
		} else {
			List<ChatListEntity> l = new ArrayList<ChatListEntity>();
			ChatListEntity listEntity = new ChatListEntity();
			listEntity.setTargetId(entity.getSenderId());
			listEntity.setUnReadNum(1);
			listEntity.setContent(entity.getContent());
			listEntity.setSendTime(entity.getSendTime());
			listEntity.setContentType(entity.getContentType());
			listEntity.setNickname(entity.getSenderNickname());
			listEntity.setCategory(entity.getCategory());
			listEntity.setAvatar(entity.getSenderAvatar());
			listEntity.getMsgList().add(entity);
			l.add(listEntity);
			ChatListMember.chatListMap.put(entity.getTargetId(), l);
		}
	}

	/**
	 * 将内存map转成json写入文件
	 */
	public synchronized void cacheMapToTxt() {

		BufferedWriter fw = null;
		try {
			File f = new File(System.getProperty("user.dir") + "/" + cacheFileName);

			if (f.exists()) {
				f.delete();
			}
			f.createNewFile();// 每次每次这个文件的内容都是新的数据

			fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, true), "UTF-8")); // 指定编码格式，以免读取时中文字符异常
			JSONArray json = JSONArray.fromObject(chatListMap); 
			fw.append(json.toString());
			fw.flush(); // 全部写入缓存中的内容
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public synchronized void txtToCacheMap() {
		String mapStr = readFileByLine(System.getProperty("user.dir") + "/" + cacheFileName);
		System.out.println("文件内容:"+mapStr);
		if (!mapStr.isEmpty() && !mapStr.equals("")) {
			JSONArray jsonArray = JSONArray.fromObject(mapStr);
			
			List<Object> jsonObjList = (List<Object>) JSONUtil.JsonToList(jsonArray);
			for (Object object : jsonObjList) {
				JSONObject jsonObject = JSONObject.fromObject(object);
				Map<String, Object> m = JSONUtil.JsonToMap(jsonObject);
				for (Object mapObj : m.keySet()) {
					List<ChatListEntity> chatListEntities = new ArrayList<ChatListEntity>();
					chatListMap.put(Long.valueOf(mapObj.toString()), chatListEntities);
					JSONArray jsonArray2 = JSONArray.fromObject(m.get(mapObj));
					List<Object> jsonObjList1 = (List<Object>) JSONUtil.JsonToList(jsonArray2);
					for (Object object2 : jsonObjList1) {
						ChatListEntity entity = (ChatListEntity) JSONObject.toBean(JSONObject.fromObject(object2), ChatListEntity.class);
						List<ChatMessageEntity> chatMessageEntities = new ArrayList<ChatMessageEntity>();
						List<Object> jsonObjList3 = (List<Object>) JSONUtil.JsonToList(JSONArray.fromObject(entity.getMsgList()));
						for (Object object3 : jsonObjList3) {
							ChatMessageEntity entity1 = (ChatMessageEntity) JSONObject.toBean(JSONObject.fromObject(object3), ChatMessageEntity.class);
							chatMessageEntities.add(entity1);
						}
						entity.setMsgList(chatMessageEntities);
						chatListEntities.add(entity);
					}
				}
			}
		}
		
		
	}

	/*
	 * 以行为单位读写文件内容
	 * 
	 * @param filePath
	 */
	public static String readFileByLine(String filePath) {
		System.out.println("文件目录:"+filePath);
		StringBuilder result = new StringBuilder();
		try {
			File f = new File(filePath);

			if (!f.exists()) {
				f.createNewFile();
			}
			
			
			BufferedReader br = new BufferedReader(new FileReader(filePath));// 构造一个BufferedReader类来读取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
				result.append(System.lineSeparator() + s);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(Thread.currentThread().getContextClassLoader().getResource("")); 
		 
		System.out.println(ChatListMember.class.getClassLoader().getResource("")); 
		 
		System.out.println(ClassLoader.getSystemResource("")); 
		System.out.println(ChatListMember.class.getResource("")); 
		System.out.println(ChatListMember.class.getResource("/")); 
		//Class文件所在路径 
		System.out.println(new File("/").getAbsolutePath()); 
		System.out.println(System.getProperty("user.dir")); 
//		String jsonStr = "[{\"1\":[{\"unReadNum\":1,\"targetId\":6,\"nickname\":\"张三\",\"avatar\":\"ios_dev_6_qiniu_20161221115519162.png\",\"msgList\":[{\"senderNickname\":\"张三\",\"senderId\":6,\"targetId\":1,\"senderAvatar\":\"ios_dev_6_qiniu_20161221115519162.png\",\"msgId\":114,\"category\":\"\",\"contentType\":0,\"content\":\"3\",\"sendTime\":\"2016-12-27 16:13:37\"}],\"category\":\"\",\"contentType\":0,\"userId\":0,\"content\":\"3\",\"sendTime\":\"2016-12-27 16:13:37\"}]}]";
////		String jsonStr = "[{\"1\":[{\"unReadNum\":1,\"msgList\":[{\"senderNickname\":\"张三\"}]},{\"unReadNum\":3,\"msgList\":[]}]},{\"2\":[{\"unReadNum\":1},{\"unReadNum\":3}]}]";
//		
//		JSONArray jsonArray = JSONArray.fromObject(jsonStr);
//		
//		List<Object> jsonObjList = (List<Object>)JSONUtil.JsonToList(jsonArray);
//		System.out.println("总的数量:"+jsonObjList.size());
//		for (Object object : jsonObjList) {
//			JSONObject jsonObject = JSONObject.fromObject(object);
//			Map<String, Object> m = JSONUtil.JsonToMap(jsonObject);
//			for (Object mapObj : m.keySet()) {
//				System.out.println("key为:"+mapObj+"值为:"+m.get(mapObj));
//				JSONArray jsonArray2 = JSONArray.fromObject(m.get(mapObj));
//				
//				List<Object> jsonObjList1 = (List<Object>) JSONUtil.JsonToList(jsonArray2);
//				
//				for (Object object2 : jsonObjList1) {
//					ChatListEntity entity = (ChatListEntity) JSONObject.toBean(JSONObject.fromObject(object2), ChatListEntity.class);
//					System.out.println("聊天列表未读数量value:"+entity.getUnReadNum());
//					
//					List<Object> jsonObjList3 = (List<Object>) JSONUtil.JsonToList(JSONArray.fromObject(entity.getMsgList()));
//					for (Object object3 : jsonObjList3) {
//						ChatMessageEntity entity1 = (ChatMessageEntity) JSONObject.toBean(JSONObject.fromObject(object3), ChatMessageEntity.class);
//						System.out.println("聊天发送者昵称:"+entity1.getSenderNickname());
//					}
//				}
//				
//				
//			}
//		}
	    

	}
}
